<template>
  <view>
	<u-navbar title="商城" :autoBack="false" bgColor="#00000000" @leftClick="toHomeFun"></u-navbar>
	<web-view :src="src"  @message="onH5Message"  ref="webview"   type="top:30px;"  ></web-view>
    <!-- <button @click="sendToH5">发送消息给 H5</button>   src="https://shop.jichacha.vip/h5/#pages/index/loadingapp" -->
  </view>
</template>
<script>
import { getUserInfo,openShop,linkShop,closeShop } from '@/api/api';
import { SHOP_H5_PAGE } from '@/config/app.js';
export default {
	data() {
	  return {
		  ks:'',
		  isopen_i:0,
		  openwebview:true,
		  intervalItem:null,
	    wv: null,
	    src: '',
		itime:0
	  }
	},
	mounted(){
		// this.loaduniJS();
	},
	onLoad(options) {
		console.log('options:', options);
		this.toOpenShop();
	},
	onUnload() {
		
	},
	onshow(){
		console.log('onshow:');
		// this.toOpenShop();
	},
	onBackPress() {
		this.toOpenShop();
		return false;
		
		// this.showBackConfirm();
		// return false;
		
		// return uni.reLaunch({
		// 	url: '/pages/tabbar/index'
		// })
	},
  methods: {
	  toHomeFun() {
	  	uni.reLaunch({
	  		url: '/pages/tabbar/index'
	  	})
	  },
	  loaduniJS() {
	        const script = document.createElement('script');
	  	  // https://gitee.com/dcloud/uni-app/raw/dev/dist/uni.webview.1.5.5.js
	  	  // https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js
	        script.src = 'static/webviewjs/uni.webview.js';
	        script.onload = () => {
	          console.log('uniJS-SDK已加载');
	          // 在这里可以调用wx.config等微信JS-SDK提供的方法
	        };
	        document.head.appendChild(script);
	  },
		setSrcUrl() {
			  let _this = this
			  let token = uni.getStorageSync('token')
			  console.log(token, '[token]');
			  
			  // _this.src = `https://shop.jichacha.vip/h5/pages/index/loading/loading?token=${token}`
			  // _this.src = `https://shop.jichacha.vip/h5/pages/index/loading/loading?token=${token}`
			  // _this.src = 'http://localhost:8080/h5/pages/index/loading?token='+token+'&ks='+this.ks;
			  // _this.src = SHOP_H5_PAGE+'#/pages/index/loading?token='+token+'&ks='+this.ks+'&isapp=1';
			  console.log(_this.src, '[src]');
			  getUserInfo().then((res) => {
				_this.src = SHOP_H5_PAGE+'#/pages/index/loading?token='+token+'&ks='+this.ks+'&isapp=1';
				console.log('getUserInfo', res);
			  }).catch(err => {
				console.log(err, '[]');
				uni.$u.toast('网络超时，请稍后再试');
			  })
		},
	toOpenShop(){
		console.log('toOpenShop');
		openShop().then((res) => {
			console.log('openShop',res);
			if(res.data.open_shop_status != 1){
				uni.$u.toast(res.data.close_shop_text);
				uni.reLaunch({
					url:'/pages/tabbar/index'
				});
				return false;
			}
			this.ks = res.data.ks;
			this.openwebview = true;
			this.setSrcUrl();
			// this.startLink();
			
		}).catch(err => {
			console.log(err, '[openShop]');
			uni.$u.toast('异常错误');
			this.openwebview = false;
			this.stopLink();
			uni.reLaunch({//url:'/pages/tabbar/cameraView'
				url:'/pages/tabbar/index'
			})
		  });
	},
	startLink(){//微信 小程使用的函数
		let i = 0;
		this.intervalItem = setInterval(() => {
					i++;
					console.log('setInterval');
					wx.setStorageSync('webviewInfo', {toAppPage:'-',toWebPage:i});
					let webviewInfo = wx.getStorageSync('webviewInfo');
					console.log('webviewInfo',webviewInfo);
				    //this.sendDataToWebView({ type: 'response', data: 'Hello from Mini Program' });
					this.toLinkShop();
				}, 1000); // 每5秒查询一次
	},
	stopLink(){//微信 小程使用的函数
		if(!this.openwebview){
			clearInterval(this.intervalItem );
			this.intervalItem  = null; // 重置以便重新启动
		}else{
			setTimeout(this.stopLink() , 1000);
		}
	},
	toLinkShop(){//微信 小程使用的函数
		console.log('toLinkShop');
		
		linkShop({ks:this.ks}).then((res) => {
			console.log('linkShop',res);
			if(res.code){
				if(!res.data.is_open){
					console.log('isopen_i',this.isopen_i);
					if(this.isopen_i<15){
						this.isopen_i++;
					}else{
						uni.$u.toast('网络超时，请稍后再试');
						this.openwebview = false;
						this.stopLink();
						uni.reLaunch({
							url:'/pages/tabbar/cameraView'
						})
					}
				}else{
					this.isopen_i = 0;
					if(res.data.out_time == 0){//关闭商城跳转走
					console.log('关闭商城跳转走');
						this.openwebview = false;
						this.stopLink();
						if(res.data.close_url != ''){
							uni.reLaunch({
								url:res.data.close_url
							})
						}else{
							uni.reLaunch({
								url:'/pages/tabbar/cameraView'
							})
						}
					}
				}
			}else{
				uni.$u.toast('数据异常，请稍后再试!');
				this.openwebview = false;
				this.stopLink();
				uni.reLaunch({
					url:'/pages/tabbar/cameraView'
				})
			}
		}).catch(err => {
			this.openwebview = false;
			this.stopLink();
			console.log(err, '[linkShop]');
			uni.$u.toast('网络超时，请稍后再试');
		  });
	},
    onH5Message(e) {
		this.itime++;
      const data = e.detail.data;
      console.log('收到 H5 数据:', data);
	  console.log( data[0]);
	  console.log( data[0]['type'], data[0].msg);
		// if(this.itime<6)this.sendToH5();
		
		// this.openwebview = false;
		// this.stopLink();
		if(data[0]['type'] == 'closeShop'){
			uni.reLaunch({//url:'/pages/tabbar/cameraView'
				url:'/pages/tabbar/index'
			})
		}
		if(data[0]['type'] == 'toapppay'){
			let jsConfig = data[0]['data'];
			let that = this
			uni.requestPayment({
				provider: 'wxpay',
				orderInfo: jsConfig,
				success: (e) => {
					let url = '';
					uni.showToast({
						title: '支付成功'
					})
					// setTimeout(res => {
					// 	uni.redirectTo({
					// 		url: url
					// 	})
					// }, 2000)
				},
				fail: (e) => {
					uni.showModal({
						content: '支付失败',
						showCancel: false,
						success: function(res) {
							// if (res.confirm) {
							// 	uni.redirectTo({
							// 		url: url
							// 	})
							// } else if (res.cancel) {}
						}
					})
				},
				complete: () => {
					uni.hideLoading();
				},
			});
		}
		
		
    },
	
    sendToH5() {//失败的 函数  可删
      // this.$refs.webview.evalJS(`
      //   uni.receiveMessage({
      //     data: { type: 'fromUniApp22333', msg: '数据来自 UniApp44565' }
      //   });
      // `);
	  const webView = this.$scope.$getAppWebview();  
	  webView.evalJS(`window.postMessageToChild({ 
        type: 'fromParent', 
        data: 'Hello from UniApp!'
      });`); 
	  
		// if (this.$refs.webview) {
	 //      // 直接调用 postMessage（无需 evalJS）
	 //      this.$refs.webview.postMessage({
	 //        type: 'fromParent',
	 //        data: 'Hello via postMessage!'
	 //      });
	 //    }
    },
	showBackConfirm() {
		
		// 显示确认弹窗（支持多平台样式）
	    if (this.isNavigating) return
	    
	    uni.showModal({
	      title: '返回提示',
	      content: '确定要退出商城吗？',
	      confirmColor: '#007AFF',  // iOS风格蓝色
	      cancelColor: '#666',      // 中性灰色
	      success: (res) => {
	        if (res.confirm) {
	          this.handleNavigation()
	        }
	      },
	      fail: (err) => {
	        console.error('弹窗显示失败:', err)
	      }
	    })
	  },
	  // 执行页面跳转（带防抖和状态管理）
	  async handleNavigation() {
	    if (this.isNavigating) return
	    this.isNavigating = true
	    
	    try {
	      await uni.reLaunch({
	        url: '/pages/tabbar/index',
	        animationType: 'fade-in', // iOS风格渐变
	        animationDuration: 250
	      })
	    } catch (e) {
	      uni.showToast({
	        title: '跳转失败',
	        icon: 'none'
	      })
	    } finally {
	      this.isNavigating = false
	    }
	  }
	
  }
}
</script>
